package basic.study.wantOffer.chapter1;

/**
 * @author Kevin
 * @date 2020/4/23 20:42
 * 把一个字符串转为整数
 */
public class Problem_1 {
    static boolean finished = false;

    public int atoi(String str) {
        str = str.trim();
        int length = str.length();
        int i = 0;
        // 解决符号问题
        boolean minus = false;
        if (str.charAt(0) == '-') {
            minus = true;
            i++;
        } else if (str.charAt(0) == '+') {
            i++;
        }
        long MIN_VALUE = Integer.MIN_VALUE;
        long MAX_VALUE = Integer.MAX_VALUE;
        long num = 0;

        for (; i < length && !finished; i++) {
            char c = str.charAt(i);
            if (c >= '0' && c <= '9') {
                num *= 10;
                num += c - '0';
            } else {//有异常符号
                num = 0;
                break;
            }
        }

        //解决最大最小和溢出问题
        if (minus && 0 - num < MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
        if (!minus && num > MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        if (i == length) {
            finished = true;
        }
        return minus?new Long(0-num).intValue():new Long(num).intValue();
    }
}
